package com.example.contact.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.contact.model.Contact
import com.example.contact.repository.ContactRepository
import com.example.featuresdk.model.User
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ContactListViewModel @Inject constructor(contactRepository: ContactRepository):ViewModel() {

    val uiState = ContactListState()

    init {

        viewModelScope.launch {

            contactRepository.getAll(User.ME.id!!).collect{

                val groupedContacts = mutableMapOf<String,MutableMap<Contact,User>>()

                it.forEach { (contact, user) ->

                    if(contact.name.isNullOrEmpty()) {
                        contact.name = user.nickname
                    }

                    //group by the first character of contact name
                    val key = contact.name!![0].uppercase()
                    if(groupedContacts.containsKey(key)) {
                        groupedContacts[key]!![contact] = user
                    }else{
                        groupedContacts[key] = mutableMapOf(Pair(contact, user))
                    }
                }

                uiState.contacts = flowOf(groupedContacts)
            }
        }
    }
}